package wang.jinggo.service.impl;

import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.health.model.Check;
import com.ecwid.consul.v1.health.model.HealthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import wang.jinggo.service.ConsulService;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author wangyj
 * @description
 * @create 2019-01-05 16:08
 **/
@Service
public class ConsulServiceImpl implements ConsulService {
    private final static Logger LOG =  LoggerFactory.getLogger(ConsulServiceImpl.class);

    @Autowired
    private ConsulClient consulClient;
    //注销serviceName未通过的服务实例
    @Override
    public List<String> clearAllFailingService() throws Exception {
        Map<String, com.ecwid.consul.v1.agent.model.Service> map = consulClient.getAgentServices().getValue();
        List<com.ecwid.consul.v1.agent.model.Service> listService = new ArrayList<>();
        if(map!=null){
            Iterator it = map.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                String key = (String)entry.getKey();
                com.ecwid.consul.v1.agent.model.Service val = (com.ecwid.consul.v1.agent.model.Service)entry.getValue();
                listService.add(val);
            }
        }
        List<String> serviceIdList = new ArrayList<>();
        if(listService!=null && listService.size()>0){
            for(com.ecwid.consul.v1.agent.model.Service service:listService){
                String serviceName = service.getService();
                List<HealthService> response = consulClient.getHealthServices(serviceName,false, null).getValue();
                for(HealthService hservice : response) {
                    // 创建一个用来剔除无效实例的ConsulClient，连接到无效实例注册的agent
                    ConsulClient clearClient = new ConsulClient(hservice.getNode().getAddress(), 8500);
                    hservice.getChecks().forEach(check -> {
                        if(check.getStatus() != Check.CheckStatus.PASSING) {
                            LOG.info("注销Consul Service实例-unregister : {}", check.getServiceId());
                            clearClient.agentServiceDeregister(check.getServiceId());
                            serviceIdList.add(check.getServiceId());
                        }
                    });
                }
            }
        }
        return serviceIdList;
    }

    //注销serviceName未通过的服务实例
    @Override
    public List<String> clearFailingServiceByName(String serviceName) throws Exception {
        List<HealthService> response = consulClient.getHealthServices(serviceName,false, null).getValue();
        List<String> serviceIdList = new ArrayList<>();
        for(HealthService hservice : response) {
            // 创建一个用来剔除无效实例的ConsulClient，连接到无效实例注册的agent
            ConsulClient clearClient = new ConsulClient(hservice.getNode().getAddress(), 8500);
            hservice.getChecks().forEach(check -> {
                if(check.getStatus() != Check.CheckStatus.PASSING) {
                    LOG.info("注销Consul Service实例-unregister : {}", check.getServiceId());
                    clearClient.agentServiceDeregister(check.getServiceId());
                    serviceIdList.add(check.getServiceId());
                }
            });
        }
        return serviceIdList;
    }
}